package com.wuwangfu.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuwangfu.entity.LogBean;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @Author jcshen
 * @Date 2023-02-27
 * @PackageName:com.wuwangfu.func
 * @ClassName: GeoRichMapFunction
 * @Description: 查询高德地图，调用map方法，new RichMapFunction，open，close
 * @Version 1.0.0
 */
public class GeoRichMapFunc extends RichMapFunction<LogBean, LogBean> {

    private transient CloseableHttpClient httpclient;

    private String key;

    public GeoRichMapFunc(String key) {
        this.key = key;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        httpclient = HttpClients.createDefault();
    }

    @Override
    public LogBean map(LogBean value) throws Exception {
        Double longitude = value.getLongitude();
        Double latitude = value.getLatitude();
        HttpGet httpGet = new HttpGet("https://restapi.amap.com/v3/geocode/regeo?&location=" + longitude + "," + latitude + "&key=" + key);
        CloseableHttpResponse response = httpclient.execute(httpGet);

        try {
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {
                //获取请求的json字符串
                String result = EntityUtils.toString(entity);
                //转成json对象
                JSONObject json = JSON.parseObject(result);
                //获取位置信息
                JSONObject regeocode = json.getJSONObject("regeocode");
                if (regeocode != null && !regeocode.isEmpty()) {
                    JSONObject address = regeocode.getJSONObject("addressComponent");
                    //获取省市区
                    value.setProvince(address.getString("province"));
                    value.setCity(address.getString("city"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.close();
        }

        return value;
    }

    @Override
    public void close() throws Exception {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}
